package com.kangyi.admin.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kangyi.admin.mapper.AdminUserMapper;
import com.kangyi.admin.mapper.FeeMapper;
import com.kangyi.admin.service.FeeService;
import com.kangyi.constant.MessageConstant;
import com.kangyi.context.BaseContext;
import com.kangyi.dto.AddFeeDTO;
import com.kangyi.dto.FeeDTO;
import com.kangyi.dto.FeeQueryDTO;
import com.kangyi.entity.Fee;
import com.kangyi.exception.PermissionsException;
import com.kangyi.result.PageResult;
import com.kangyi.vo.AdminUserVO;
import com.kangyi.vo.FeeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Blank
 * @version 1.0
 */
@Service
public class FeeServiceImpl implements FeeService {

    @Autowired
    private FeeMapper feeMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    // 调用后检查当前线程id是否有足够的权限进行后续操作
    public void validateUserPermissions() {
        Integer currentId = BaseContext.getCurrentId();
        AdminUserVO adminUserVO = adminUserMapper.selectById(currentId);
        // 判断权限是否既不是1也不是2，如果是则抛出异常
        if (!adminUserVO.getPermissions().equals(1) && !adminUserVO.getPermissions().equals(2)) {
            throw new PermissionsException(MessageConstant.INSUFFICIENT_PRIVILEGE);
        }
    }
    @Override
    public PageResult pageQuery(FeeQueryDTO feeQueryDTO) {
        validateUserPermissions();
        PageHelper.startPage(feeQueryDTO.getPage(),feeQueryDTO.getPageSize());
        Page<FeeVO> page = feeMapper.pageQuery(feeQueryDTO);
        long total = page.getTotal();
        List<FeeVO> result = page.getResult();
        return new PageResult(total,result);
    }

    @Override
    public void addFee(AddFeeDTO addFeeDTO) {
        validateUserPermissions();
        Fee fee = new Fee();
        BeanUtil.copyProperties(addFeeDTO,fee);
        feeMapper.addFee(fee);
    }

    @Override
    public void deleteFee(List<Integer> ids) {
        validateUserPermissions();
        feeMapper.deleteFee(ids);
    }

    @Override
    public FeeVO getFee(Integer id) {
        validateUserPermissions();
        return feeMapper.getFee(id);
    }

    @Override
    public void updateFee(FeeDTO feeDTO) {
        validateUserPermissions();
        Fee fee = new Fee();
        BeanUtil.copyProperties(feeDTO,fee);
        feeMapper.updateFee(fee);
    }


}
